import torch

torch.manual_seed(10)
lr = 0.1
# 训练数据
x = torch.rand(20,1)*10
y = 2*x+(5+torch.randn(20,1))
# 参数
w = torch.randn((1),requires_grad=True)
b = torch.zeros((1),requires_grad=True)
print(w)
print(b)
for iteration in range(1000):
    # 前向传播
    wx = torch.mul(w,x)
    y_pred = torch.add(wx,b)
    # 计算MSEloss
    loss = (0.5*(y-y_pred)**2).mean()
    # 反向传播
    loss.backward()
    # 更新参数
    b.data.sub_(lr*b.grad)
    w.data.sub_(lr*w.grad)
    if loss.data.numpy()<1:
        break